package com.yanyu.space.common.core.util;

import com.alibaba.fastjson.JSONObject;
import com.yanyu.space.common.core.bean.enums.IRCode;
import com.yanyu.space.common.core.bean.web.R;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author yanyu
 */
public class WebUtil {

    /**
     * 获取请求
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if(attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            return request;
        }
        return null;
    }

    /**
     * 获取响应
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if(attributes != null) {
            HttpServletResponse response = attributes.getResponse();
            return response;
        }
        return null;
    }

    /**
     * 获取请求路径
     *
     * @return
     */
    public static String getUrl() {
        return getRequest().getRequestURI();
    }

    /**
     * 获取请求方法
     *
     * @return
     */
    public static String getMethod() {
        return getRequest().getMethod();
    }

    /**
     * 输出
     *
     * @param response
     * @param irCode
     */
    public static void out(HttpServletResponse response, IRCode irCode) {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (PrintWriter pw = response.getWriter()) {
            pw.write(JSONObject.toJSONString(R.fail(irCode)));
        } catch (IOException e) {
        }
    }
}
